<template>
	<view class="u-wrap u-p-l-20 u-p-r-20">
		<u-form :model="addModel" ref="form1">
			<u-form-item prop="introduce" label-width="auto" label="简介: ">
				<textarea :auto-height="true" maxlength="100" placeholder="请输入简介"
					v-model="addModel.introduce" />
			</u-form-item>
			<u-form-item prop="name" label-width="auto" label="类型:">
				<u-radio-group v-model="addModel.name">
					<u-radio @change="radioChange" activeColor="#ff0000" v-for="(item, index) in list" :key="index"
						:name="item.name" :disabled="item.disabled">
						{{ item.name }}
					</u-radio>
				</u-radio-group>
			</u-form-item>
			<u-form-item prop="typeName" label-width="auto" label="分类:">
				<u-input @click="openSelect" :disabled="true" placeholder="请选择分类" v-model="addModel.typeName" />
				<u-select @confirm="selectConfirm" v-model="show" :list="selectList"></u-select>
			</u-form-item>
			<u-form-item prop="price" label-width="auto" label="价格:">
				<u-input placeholder="请输入价格" v-model="addModel.price" />
			</u-form-item>
			<u-form-item prop="wxId" label-width="auto" label="联系方式:">
				<u-input placeholder="请输入微信号或QQ号(格式为:微信:***QQ:***)" v-model="addModel.wxId" />
			</u-form-item>
			<u-form-item prop="image" label-width="auto" label="图片:(默认第一张图片为主图)"></u-form-item>
			<u-upload ref="imgRef" @onChange='onChange' @onRemove='onRemove' :action="uploadUrl"
				max-count="6"></u-upload>
		</u-form>
		<u-button @click="commit" :custom-style="customStyle">发布</u-button>
	</view>
</template>

<script setup>
	import {
		reactive,
		ref
	} from 'vue';
	import {
		onReady, onShow
	} from '@dcloudio/uni-app'
	import http from '../../common/http.js';
	import {
		categoryApi,
		releaseApi
	} from '../../api/goods.js'
	//表单ref属性
	const form1 = ref()
	// import {
	// 	uploadImageApi
	// } from '../../api/write.js'
	const imgRef = ref()
	const addModel = reactive({
		userId: uni.getStorageSync('userId'),
		name: '',
		type: '',
		typeName: '',
		categoryId: '',
		introduce: '',
		price: '',
		wxId: '',
		image: ''
	})
	const list = [{
			value: '0',
			name: '闲置',
			disabled: false
		},
		{
			value: '1',
			name: '求购',
			disabled: false
		}
	]
	const rules = reactive({ //表单验证规则
		name: [{
			required: true,
			message: '请选择类型',
			trigger: ['change', 'blur'],
		}],
		typeName: [{
			required: true,
			message: '请选择分类',
			trigger: ['change', 'blur'],
		}],
		introduce: [{
			required: true,
			message: '请填写描述',
			trigger: ['change', 'blur'],
		}],
		price: [{
			required: true,
			message: '请填写价格',
			trigger: ['change', 'blur'],
		}],
		wxId: [{
			required: true,
			message: '请填写微信号或QQ号',
			trigger: ['change', 'blur'],
		}],
		image: [{
			required: true,
			message: '请至少上传一张图片',
			trigger: ['change', 'blur'],
		}],
	})
	const value = ref('')
	const uploadUrl = ref(http.baseUrl + '/api/upload/uploadImage')


	const customStyle = reactive({
		background: '#ff0000',
		color: '#FFF',
		marginTop: '50px',
		width: '100%'
	})
	//图片地址
	const imgUrl = ref([]);
	//图片上传后触发
	const onChange = (res, index, lists, name) => {
		console.log(res.data)
		//转为JSON
		let result = JSON.parse(res.data)
		imgUrl.value.push(http.baseUrl + result.data);
		//把图片路径拼接为逗号分隔的字符串,存在一个数组里
		let url = "";
		for (let k = 0; k < imgUrl.value.length; k++) {
			url = url + imgUrl.value[k] + ",";
		}
		//去掉末尾的逗号
		addModel.image = url.substring(0, url.lastIndexOf(","));
		console.log(addModel)
	}
	//删除图片时触发
	const onRemove = (index) => {
		imgUrl.value.splice(index, 1);
		let url = "";
		for (let k = 0; k < imgUrl.value.length; k++) {
			url = url + imgUrl.value[k] + ",";
		}
		//去掉末尾的逗号
		addModel.image = url.substring(0, url.lastIndexOf(","));
	}
	//分类弹框
	const show = ref(false)
	//分类数据
	const selectList = ref([])
	const getSelectList = async () => {
		let res = await categoryApi()
		if (res && res.code == 200) {
			console.log(res)
			selectList.value = res.data; //把请求的数据保存到selectList数组中
		}
	}
	//点击分类事件时打开分类弹框
	const openSelect = () => {
		show.value = true
	}
	//分类确定
	const selectConfirm = (e) => { //将用户所选的商品分类以数组形式存储在e中
		addModel.typeName = e[0].label;
		addModel.categoryId = e[0].value
		console.log(addModel)
	}
	//发布提交
	const commit = () => {
		if(addModel.price < 0){
			uni.showToast({
				title: '价格不能是负数',
				icon: 'none'
			})
		} else {
			form1.value.validate(async (valid) => {
				console.log(valid)
				if (valid) {
					let res = await releaseApi(addModel)
					if (res && res.code == 200) {
						console.log(res)
						if (addModel.type == '0') {
							uni.switchTab({
								url: '../unused/unused' //选择闲置提交后时跳转至闲置页面
							})
						} else {
							uni.switchTab({
								url: '../buy/buy' //选择求购提交后跳转至求购页面
							})
						}
						//清空数据
						form1.value.resetFields()
						imgUrl.value = []
						addModel.image = ''
						//fileList.value = []
						imgRef.value.clear()
					}
				}
			})
			console.log(addModel)
		}
	}
	//类型点击事件
	const radioChange = (e) => {
		for (let i = 0; i < list.length; i++) {
			if (list[i].name == e) {
				addModel.type = list[i].value;
				console.log(addModel)
			}
		}
	}
	onReady(() => {
		//设置表单验证规则
		form1.value.setRules(rules);
		//获取分类数据
		getSelectList();
	})
	onShow(()=>{
		//检查是否登录
		const test = uni.getStorageSync('userId')
		if(test){
			console.log("身份核验成功")			
		} else {		
			uni.switchTab({
				url: '../mine/mine'
			})
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			})
		}
	})
</script>

<style>

</style>